# -*- coding: utf-8 -*-

from odoo import api, fields, models, _
import logging
_logger = logging.getLogger(__name__)

# 调整初始化算法


class AccountMoveLine(models.Model):
    _inherit = "account.move.line"

    cash_flow_tag = fields.Many2one('account.analytic.tag', string='现金流量标签')

    # 资产+费用=负债+所有者权益+收入
    @api.depends('debit', 'credit')
    def _store_balance(self):
        for line in self:
            #如果指定了余额计算法
            if line.account_id.is_use_balance_calculate:
                if line.account_id.balance_calculate == 'debit':
                    line.balance = line.debit - line.credit
                else:
                    line.balance = line.credit - line.debit
            else:    
                # 如果科目是负债类 所有者权益
                if line.account_id.group_id.code_prefix == '2' or line.account_id.group_id.code_prefix == '4':
                    line.balance = line.credit - line.debit
                # 损益类->除费用,收入成本以外类型
                elif line.account_id.group_id.code_prefix == '6' and line.account_id.user_type_id.id != 16 and line.account_id.user_type_id.id != 17:
                    line.balance = line.credit - line.debit
                # 资产类->折旧类型
                elif line.account_id.group_id.code_prefix == '1' and line.account_id.user_type_id.id == 15:
                    line.balance = line.credit - line.debit
                else:
                    # 资产类 成本类 损益类->费用类型
                    line.balance = line.debit - line.credit


class AccountMove(models.Model):
    _inherit = "account.move"

    @api.multi
    def post(self, invoice=False):
        result = super(AccountMove, self).post(invoice)
        for record in self:
            for line in record.line_ids:
                line._store_balance()
        return result
